//! # 链路链接
//!
//! 分为`本地链接`和`远端链接`

use crate::error::*;
use alloc::boxed::Box;
use async_trait::async_trait;
use bytes::Bytes;
use core::fmt;
use core::ops::{Deref, DerefMut};

type C = Box<dyn ConnectionDriver>;
pub struct Connection(C);
impl Connection {
    pub fn new(c: C) -> Connection {
        Connection(c)
    }
}
impl Deref for Connection {
    type Target = C;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
impl DerefMut for Connection {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

/// 链路驱动接口
#[async_trait]
pub trait ConnectionDriver: Send {
    /// 是否为子网链路
    fn is_subnet(&self) -> bool;
    /// 获取类型标识
    fn kind(&self) -> &str;
    /// 获取自定义标识
    fn id(&self) -> &str;

    /// 发送数据
    async fn send(&mut self, buf: Bytes) -> Result<(), SendError>;
    /// 接收数据(可尝试重新连接)
    async fn recv(&mut self) -> Result<Bytes, RecvError>;
}
impl PartialEq for dyn ConnectionDriver {
    fn eq(&self, other: &Self) -> bool {
        self.is_subnet() == other.is_subnet()
            && self.kind() == other.kind()
            && self.id() == other.id()
    }
}
impl fmt::Display for dyn ConnectionDriver {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "connection-{}", self.kind())
    }
}
impl fmt::Debug for dyn ConnectionDriver {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "connection-{}({})", self.kind(), self.id())
    }
}
